package com.wgz.medicalmanagement.infrastructure.security;

import java.io.IOException;

import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wgz.medicalmanagement.common.entity.Result;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * JWT认证入口点，处理未认证的请求
 * 由于已移除权限限制，此处只记录未授权访问但不阻止请求
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    /**
     * 当用户尝试访问安全的REST资源且未提供有效的认证信息时，此方法将被调用
     * 因为系统已移除权限限制，这里只是记录日志并返回友好提示，但不会阻止访问
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        // 仅记录日志，不阻止访问
        log.debug("未认证访问: {} - {}", request.getRequestURI(), authException.getMessage());
        
        // 返回友好信息而不是错误
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        objectMapper.writeValue(
            response.getOutputStream(),
            Result.success("允许匿名访问", null)
        );
    }
} 